package com.beaven.model.data.group;

import android.text.TextUtils;
import com.beaven.model.data.helper.DbHelper;
import com.beaven.model.data.helper.UserHelper;
import com.beaven.model.model.card.GroupCard;
import com.beaven.model.model.db.Group;
import com.beaven.model.model.db.User;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/6/2 10:36
 */

public class GroupDispatcher implements GroupCenter {

  private static volatile GroupDispatcher instance;

  public static GroupDispatcher getInstance() {
    if (instance == null) {
      synchronized (GroupDispatcher.class) {
        if (instance == null) {
          instance = new GroupDispatcher();
        }
      }
    }
    return instance;
  }

  private GroupDispatcher() {
  }

  private List<Group> groupList;

  @Override public void dispatchGroup(GroupCard... cards) {
    groupList = new ArrayList<>();
    Observable.from(cards).subscribeOn(Schedulers.io()).subscribe(new Subscriber<GroupCard>() {
      @Override public void onCompleted() {
        DbHelper.instance().saveModel(Group.class, groupList.toArray(new Group[0]));
      }

      @Override public void onError(Throwable e) {
        Timber.e("群组分发-Error--" + e);
      }

      @Override public void onNext(GroupCard groupCard) {
        if (!TextUtils.isEmpty(groupCard.getId())) {
          User user = UserHelper.findFromLocal(groupCard.getOwnerId());
          groupList.add(groupCard.build(user));
        }
      }
    });
  }
}
